package cn.com.zcode.core.cxf.client;

import java.lang.reflect.Type;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

import org.apache.log4j.Logger;

public class BaseConvert implements Convert  {
	Logger logger = Logger.getLogger(BaseConvert.class);

	@Override
	public Object format(Object obj, Type fileld) {
		if (obj instanceof XMLGregorianCalendar) {
			Object newobj = convertToDate((XMLGregorianCalendar) obj);
			logger.debug("Convert format Info: " + obj + " -> " + newobj);
			obj = newobj;
		}

		return obj;

	}

	@Override
	public Object parse(Object obj) {
		if (obj instanceof Date) {
			Object newobj = convertToXMLGregorianCalendar((Date) obj);
			logger.debug("Convert parse Info: " + obj + " -> " + newobj);
			obj = newobj;
		}
		return obj;
	}

	private Date convertToDate(XMLGregorianCalendar cal) {
		GregorianCalendar ca = cal.toGregorianCalendar();
		return ca.getTime();
	}

	private XMLGregorianCalendar convertToXMLGregorianCalendar(Date date) {
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(date);
		XMLGregorianCalendar gc = null;
		try {
			gc = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return gc;
	}
}
